package bb.lanxing.activity.mine;

import static android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION;
import static android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
import static android.provider.MediaStore.ACTION_IMAGE_CAPTURE;
import static android.text.InputType.TYPE_CLASS_NUMBER;
import static android.text.InputType.TYPE_NUMBER_FLAG_DECIMAL;
import static bb.lanxing.common.config.Constants.FILE_PROVIDER;
import static bb.lanxing.common.config.Constants.REQUEST_PREFIX;
import static bb.lanxing.common.config.Constants.TEMP_FILE_NAME;
import static bb.lanxing.lib.devices.sprint.entity.SettingSupports.SUPPORT_ITEM_NICK_NAME;
import static bb.lanxing.network.MyHttpClient.DOMAIN;

import java.io.File;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import com.umeng.socialize.net.dplus.CommonNetImpl;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;

import bb.lanxing.App;
import bb.lanxing.MainActivity;
import bb.lanxing.R;
import bb.lanxing.activity.CityChooseActivity;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.common.config.Constants;
import bb.lanxing.lib.devices.sprint.entity.SettingSupports;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.User;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetSubscribe;
import bb.lanxing.util.AppFileUtils;
import bb.lanxing.util.BirthdaySelectDialogUtil;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.FileProviderUtil;
import bb.lanxing.util.InputHelper;
import bb.lanxing.util.RxPermissionUtil;
import bb.lanxing.util.UriParse;
import bb.lanxing.util.UserAvatarUtil;
import bb.lanxing.utils.DateUtil;
import bb.lanxing.view.BiciAlertDialogBuilder;
import bb.lanxing.view.UserAvatarView;
import kotlin.Unit;
import okhttp3.Call;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ProfileEditActivity extends BaseActivity {
    public static final int TYPE_DETAIL = 2;
    public static final int TYPE_SIMPLE = 1;
    private static final int IMAGE_FROM_CROPPING = 2;
    private static final int IMAGE_FROM_FILE = 1;
    private static final int IMAGE_FROM_PHOTO = 0;
    private static final String TEMP_IMAGE = "photo_temp.png";
    private static final String UPLOAD_IMAGE = "userChoosingAvatar.png";
    private Spinner ageSpinner;
    private TextView cityBadgeView;
    private TextView cityView;
    private File cropTempFile = null;
    private TextView genderView;
    private Spinner heightSpinner;
    private File imageFile;
    private Dialog imageSelectDialog;
    private LinearLayout llBirthDay;
    private View mCityContainer;
    private View mCommitBtn;
    private View mGenderContainer;
    private View mNicknameContainer;
    private View mPhotoContainer;
    private View mWeightContainer;
    private TextView nicknameView;
    private String photoDir;
    private LinearLayout simpleContainer;
    private TextView txtBirthDay;
    private int type;
    private UserAvatarView userAvatar;
    private User userMy;
    private TextView weightView;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_profile_edit);
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        initView();
        String local = getResources().getConfiguration().locale.toString();
        Log.i("ProfileEditActivity", "ProfileEditActivity onCreate = " + local);
    }

    private void initView() {
        int intExtra = getIntent().getIntExtra("type", TYPE_DETAIL);
        type = intExtra;
        if (intExtra == TYPE_SIMPLE) {
            simpleContainer.setVisibility(View.VISIBLE);
        } else {
            simpleContainer.setVisibility(View.GONE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    public void loadData() {
        long userId = SharedManager.getInstance().getUserId();
        if (0 == userId) {
            finish();
            return;
        }
        User user = User.getUserByUid(userId);
        userMy = user;
        if (userMy == null) {
            finish();
            return;
        }
        if (userMy.getBirthday() != 0) {
            try {
                DateUtil.date(txtBirthDay, userMy.getBirthday());
            } catch (Exception e) {
                Log.e("birthday", Objects.requireNonNull(e.getMessage()));
            }
        }
        userAvatar.setAvatarMode(UserAvatarView.AVATAR_SIZE_48);
        if (userMy.getPhotoUrl() != null) {
            userAvatar.setAvatarForUrl(userMy.getPhotoUrl());
        }
        nicknameView.setText(userMy.getNickName());
        String str = "";
        if (!TextUtils.isEmpty(userMy.getProvince()) && !CommonUtil.isCityCountOne(userMy.getProvince())) {
            str = userMy.getProvince() + " ";
        }
        if (!TextUtils.isEmpty(userMy.getCity())) {
            str = str + userMy.getCity();
        }
        if (TextUtils.isEmpty(str)) {
            cityView.setText(R.string.value_not_setting);
            cityBadgeView.setVisibility(View.VISIBLE);
        } else {
            cityView.setText(str);
            cityBadgeView.setVisibility(View.GONE);
        }
        genderView.setText(
                getString(userMy.getGender() == 1 ? R.string.mine_profile_male : R.string.mine_profile_female));
        double weight = userMy.getWeight();
        weightView.setText(MessageFormat.format("{0,number,#.#}kg", weight));
        initAge();
        initHeight();
    }

    private void initAge() {
        int i = 90;
        final Integer[] numArr = new Integer[90];
        int i2 = 0;
        while (i2 < 90) {
            int i3 = 1 + i2;
            numArr[i2] = i3;
            i2 = i3;
        }
        ArrayAdapter<Integer> arrayAdapter = new ArrayAdapter<>(this, R.layout.my_spinner_check_text, numArr);
        arrayAdapter.setDropDownViewResource(R.layout.my_spinner_item);
        ageSpinner.setAdapter(arrayAdapter);
        int age = userMy.getAge();
        if (age < 1) {
            i = 1;
        } else if (age <= 90) {
            i = age;
        }
        ageSpinner.setSelection(i - 1);
        ageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i4, long j) {
                if (i4 < numArr.length) {
                    changeAge(numArr[i4]);
                }
            }
        });
    }

    private void initHeight() {
        final Integer[] numArr = new Integer[181];
        for (int i = 0; i < 181; i++) {
            numArr[i] = 50 + i;
        }
        ArrayAdapter<Integer> arrayAdapter = new ArrayAdapter<>(this, R.layout.my_spinner_check_text, numArr);
        arrayAdapter.setDropDownViewResource(R.layout.my_spinner_item);
        heightSpinner.setAdapter(arrayAdapter);
        int height = userMy.getHeight();
        if (height == 0) {
            changeHeight(Constants.HEIGHT_DEFAULT);
        } else {
            if (height < Constants.HEIGHT_LOW) {
                height = Constants.HEIGHT_LOW;
            } else if (height > Constants.HEIGHT_HEIGHT) {
                height = Constants.HEIGHT_HEIGHT;
            }
        }
        heightSpinner.setSelection(height - 50);
        heightSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i2, long j) {
                if (i2 < numArr.length) {
                    changeHeight(numArr[i2]);
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_profile_edit, menu);
        menu.findItem(R.id.action_skip).setVisible(type == 1);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem menuItem) {
        if (R.id.action_skip == menuItem.getItemId()) {
            onNextBtnClick(menuItem.getActionView());
        }
        return super.onOptionsItemSelected(menuItem);
    }

    public void onNextBtnClick(View view) {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    public void onAvatarClick(View view) {
        String photoUrl = userMy.getBigPhoto();
        if (!TextUtils.isEmpty(photoUrl)) {
            UserAvatarUtil.getInstance().showUserAvatarBig(this, photoUrl);
        }
    }

    public void onPhotoContainerClick(View view) {
        checkCameraAndStoragePermission();
    }

    public void onCityClick(View view) {
        startActivity(new Intent(this, CityChooseActivity.class));
    }

    public void onGenderClick(View view) {
        showGenderDialog();
    }

    public void onNicknameClick(View view) {
        showEditDialog("nickname", userMy.getNickName());
    }

    public void onWeightClick(View view) {
        showEditDialog("weight", String.valueOf(userMy.getWeight()));
    }

    private void showEditDialog(final String str, final String str2) {
        View inflate = LayoutInflater.from(this).inflate(R.layout.edittext_view, null);
        final EditText editText = inflate.findViewById(R.id.editText);
        editText.setMaxLines(1);
        if (TextUtils.isEmpty(str2)) {
            editText.setHint(R.string.dialog_hint_input);
        } else {
            editText.setText(str2);
        }
        AlertDialog.Builder negativeButton = new BiciAlertDialogBuilder(this).setView(inflate)
                .setPositiveButton(R.string.dialog_btn_ok, (dialogInterface, i) -> {
                    String obj = editText.getText().toString();
                    if (TextUtils.isEmpty(obj) || obj.equals(str2)) {
                        dialogInterface.cancel();
                    } else if ("nickname".equals(str)) {
                        changNickname(obj);
                    } else if ("weight".equals(str)) {
                        changeWeight(Double.parseDouble(obj));
                    }
                    InputHelper.hideSoftInput(editText);
                }).setNegativeButton(R.string.dialog_btn_cancel,
                        (dialogInterface, i) -> InputHelper.hideSoftInput(editText));
        if ("nickname".equals(str)) {
            negativeButton.setTitle(R.string.mine_profile_dialog_title_change_nickname);
        } else if ("weight".equals(str)) {
            negativeButton.setTitle(R.string.mine_profile_dialog_title_change_weight);
            editText.setInputType(TYPE_NUMBER_FLAG_DECIMAL | TYPE_CLASS_NUMBER);
        }
        negativeButton.show();
        InputHelper.showSoftInput(editText);
    }

    private void showGenderDialog() {
        final int gender = userMy.getGender();
        new BiciAlertDialogBuilder(this).setTitle(R.string.mine_profile_dialog_title_choose_gender)
                .setItems(
                        new String[] { getString(R.string.mine_profile_female), getString(R.string.mine_profile_male) },
                        (dialogInterface, i) -> {
                            if (i != gender) {
                                changeGender(i);
                            }
                        })
                .show();
    }

    public void changeGender(int i) {
        requestUpdate(CommonNetImpl.SEX, String.valueOf(i));
    }

    public void changeAge(int i) {
        if (i == userMy.getAge()) {
            return;
        }
        requestUpdate(SettingSupports.SUPPORT_ITEM_AGE, String.valueOf(i));
    }

    public void changeHeight(int i) {
        if (i == userMy.getHeight()) {
            return;
        }

        requestUpdate("height", String.valueOf(i));
    }

    public void changeWeight(double d) {
        if (d < 20.0 || d > 150.0) {
            App.getContext().showMessage(R.string.mine_profile_toast_input_valid_weight);
        } else if (d != userMy.getWeight()) {
            requestUpdate("weight", String.valueOf(d));
        }
    }

    public void changNickname(String str) {
        if (str.length() > 15) {
            App.getContext().showMessage(R.string.mine_profile_toast_nickname_too_long);
        } else {
            requestUpdate(SUPPORT_ITEM_NICK_NAME, str);
        }
    }

    private void requestUpdate(final String key, final String value) {
        BiCiCallback biCiCallback = new BiCiCallback() {
            @Override
            public void onResponseString(@NonNull String str3) {
                updateUserData(key, value);
            }
        };
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put(key, value);
        MyHttpClient.updateUserInfo(biCiCallback, hashMap);
    }

    private void updateUserData(String key, String value) {
        ContentValues c = new ContentValues();
        if (SUPPORT_ITEM_NICK_NAME.equals(key)) {
            userMy.setNickName(value);
            c.put(SUPPORT_ITEM_NICK_NAME, value);
        } else if ("email".equals(key)) {
            userMy.setEmail(value);
            c.put("email", value);
        } else if (CommonNetImpl.SEX.equals(key)) {
            userMy.setGender(Integer.parseInt(value));
            c.put("gender", value);
        } else if (SettingSupports.SUPPORT_ITEM_AGE.equals(key)) {
            userMy.setAge(Integer.parseInt(value));
            c.put(SettingSupports.SUPPORT_ITEM_AGE, value);
        } else if ("avatar".equals(key)) {
            userMy.setPhotoUrl(value);
            c.put("photoUrl", value);
        } else if ("height".equals(key)) {
            userMy.setHeight(Integer.parseInt(value));
            c.put("height", value);
        } else if ("weight".equals(key)) {
            userMy.setWeight(Double.parseDouble(value));
            c.put("weight", value);
        } else if ("birthday".equals(key)) {
            userMy.setBirthday(Long.parseLong(value));
            c.put("birthday", value);
        }
        App.getContext().setUserDataChanged(true);
        LitePal.update(User.class, c, userMy.getId());

        runOnUiThread(this::loadData);
    }

    private void checkCameraAndStoragePermission() {
        if (RxPermissionUtil.getInstance().checkPermission(this, RxPermissionUtil.getCameraPermission())) {
            uploadImage();
        } else {
            requestCameraAndStoragePermission();
        }
    }

    private void requestCameraAndStoragePermission() {
        RxPermissionUtil.getInstance().setPermissions(RxPermissionUtil.getCameraPermission())
                .permissionRequestEachCombined(this, new RxPermissionUtil.PermissionCallBack() {
                    @Override
                    public void granted() {
                        if (!App.isManagersInit) {
                            App.getContext().initManagersWithPermissions();
                        }
                        uploadImage();
                    }

                    @Override
                    public void deny() {
                        App.getContext().showMessage("拍照存储权限已拒绝");
                    }
                });
    }

    private void uploadImage() {
        if (!AppFileUtils.isSdCardAvailable()) {
            App.getContext().showMessage(R.string.sdcard_null);
            return;
        }
        photoDir = AppFileUtils.buildExternalDirectoryPath(Constants.PHOTO);
        Log.d(Constants.TAG, "photoDir = " + photoDir);
        if (photoDir == null) {
            return;
        }
        imageSelectDialog = new BiciAlertDialogBuilder(this).setTitle(R.string.dialog_choose_image).setItems(
                new CharSequence[] { getText(R.string.dialog_take_photo), getText(R.string.dialog_photo_album) },
                (dialogInterface, i) -> {
                    if (i == 1) {
                        Intent intent = new Intent(Intent.ACTION_PICK, null);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION);
                        try {
                            startActivityForResult(intent, IMAGE_FROM_FILE);
                        } catch (Exception unused) {
                            App.getContext().showMessage("找不到可以处理图片的应用。");
                        }
                    } else {
                        imageFile = new File(photoDir + ProfileEditActivity.TEMP_IMAGE);
                        Intent intent = new Intent(ACTION_IMAGE_CAPTURE);
                        intent.putExtra("output",
                                FileProvider.getUriForFile(App.getContext(), FILE_PROVIDER, imageFile));
                        intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION);
                        try {
                            startActivityForResult(intent, IMAGE_FROM_PHOTO);
                        } catch (Exception e) {
                            e.printStackTrace();
                            App.getContext().showMessage(R.string.permission_request_permission_tips);
                        }
                    }
                }).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == IMAGE_FROM_PHOTO) {
            cropImageUri(FileProviderUtil.getUriForFile(this, imageFile));
        } else if (requestCode == IMAGE_FROM_CROPPING) {
            Dialog dialog = imageSelectDialog;
            if (dialog != null) {
                dialog.dismiss();
            }
            uploadImageToUPYun();
            userAvatar.setNormalAvatar(userMy.getPhotoUrl());
            // HeaderUtil.INSTANCE.setHeader(userAvatar, getContentResolver());
        } else {
            Uri uri = null;
            try {
                String path = UriParse.getPath(App.getContext(), intent.getData());
                if (path != null) {
                    File file = new File(AppFileUtils.buildExternalDirectoryPath(Constants.PHOTO));
                    File file2 = new File(file + File.separator + UPLOAD_IMAGE);
                    if (file2.exists()) {
                        file2.deleteOnExit();
                    }
                    AppFileUtils.copyFile(new File(path), file, UPLOAD_IMAGE);
                    App context = App.getContext();
                    uri = FileProvider.getUriForFile(context, FILE_PROVIDER,
                            new File(file + File.separator + UPLOAD_IMAGE));
                }
                cropImageUri(uri);
            } catch (NullPointerException unused) {
                Toast.makeText(this, R.string.profile_entry_activity_load_img_error, Toast.LENGTH_SHORT).show();
            }
        }
    }

    protected void cropImageUri(Uri uri) {
        String buildExternalDirectoryPath = AppFileUtils.buildExternalDirectoryPath(Constants.PHOTO);
        if (buildExternalDirectoryPath == null) {
            return;
        }
        File file = new File(buildExternalDirectoryPath, TEMP_FILE_NAME);
        cropTempFile = file;
        if (file.exists()) {
            file.delete();
        }
        Uri uriForFile = FileProvider.getUriForFile(App.getContext(), FILE_PROVIDER, cropTempFile);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        intent.setClipData(ClipData.newRawUri("output", uriForFile));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 640);
        intent.putExtra("outputY", 640);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra("output", uriForFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, IMAGE_FROM_CROPPING);
    }

    private void grantPermissionFix(Intent intent, Uri uri) {
        intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION);
        for (ResolveInfo resolveInfo : getPackageManager().queryIntentActivities(intent, 65536)) {
            try {
                grantUriPermission(resolveInfo.activityInfo.packageName, uri,
                        FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION);
                intent.setAction(null);
                intent.setComponent(
                        new ComponentName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name));
                return;
            } catch (Exception unused) {
            }
        }
    }

    private void uploadImageToUPYun() {
        showMyProgressDialog(R.string.toast_uploading_avatar);
        Call uploadAvatar = MyHttpClient.uploadAvatar(cropTempFile);
        Observable.create(new NetSubscribe(uploadAvatar)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable th) {
                        toast(R.string.toast_upload_image_failed);
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onNext(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            try {
                                JSONObject jsonObject = new JSONObject(str);
                                int code = jsonObject.optInt("code");
                                if (200 == code) {
                                    String url = jsonObject.optString("imgUrl", "");
                                    toast(R.string.toast_upload_image_successful);
                                    String str2 = DOMAIN + REQUEST_PREFIX + url;
                                    userMy.setPhotoUrl(str2);
                                    userMy.save();
                                    requestUpdate("avatar", str2);
                                    App.getContext().setSigninUser(userMy);
                                    userAvatar.setNormalAvatar(userMy.getPhotoUrl());
                                }
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            toast(R.string.toast_upload_image_failed);
                        }
                    }
                });
    }

    private void bindView(View view) {
        userAvatar = view.findViewById(R.id.userAvatar);
        nicknameView = view.findViewById(R.id.nicknameView);
        genderView = view.findViewById(R.id.genderView);
        cityView = view.findViewById(R.id.cityView);
        cityBadgeView = view.findViewById(R.id.cityBadgeView);
        ageSpinner = view.findViewById(R.id.ageSpinner);
        heightSpinner = view.findViewById(R.id.heightSpinner);
        simpleContainer = view.findViewById(R.id.simpleContainer);
        weightView = view.findViewById(R.id.weightView);
        mCommitBtn = view.findViewById(R.id.commitBtn);
        mPhotoContainer = view.findViewById(R.id.photoContainer);
        mCityContainer = view.findViewById(R.id.cityContainer);
        mGenderContainer = view.findViewById(R.id.genderContainer);
        mNicknameContainer = view.findViewById(R.id.nicknameContainer);
        mWeightContainer = view.findViewById(R.id.weightContainer);
        txtBirthDay = view.findViewById(R.id.txt_birthday);
        llBirthDay = view.findViewById(R.id.ll_birthday);
        mCommitBtn.setOnClickListener(this::onNextBtnClick);
        userAvatar.setOnClickListener(this::onAvatarClick);
        mPhotoContainer.setOnClickListener(this::onPhotoContainerClick);
        mCityContainer.setOnClickListener(this::onCityClick);
        mGenderContainer.setOnClickListener(this::onGenderClick);
        mNicknameContainer.setOnClickListener(this::onNicknameClick);
        mWeightContainer.setOnClickListener(this::onWeightClick);
        llBirthDay.setOnClickListener(this::onBirthdayClick);
    }

    public void onBirthdayClick(View view) {
        BirthdaySelectDialogUtil.Companion.showBirthDialog(this, userMy.getBirthday(), l -> {
            DateUtil.date(txtBirthDay, l);
            requestUpdate("birthday", l.toString());
            return Unit.INSTANCE;
        });
    }
}
